// 导入router的hook
import { useParams, useHistory } from 'react-router-dom'
import { Card, Breadcrumb, Form, Input, Button, Radio, Upload, message } from 'antd'
import { PlusOutlined } from '@ant-design/icons'

import Channels from '@/components/Channels'
import { Link } from 'react-router-dom'
import style from './index.module.scss'

// 富文本编辑器
import ReactQuill from 'react-quill' // ES6
import 'react-quill/dist/quill.snow.css' // ES6
import { useState } from 'react'
import { addAritcle } from '@/api'

// 封面的多种选项
const types = [
  { id: 1, value: '单图' },
  { id: 3, value: '三图' },
  { id: 0, value: '无图' },
]
/*
  1. 如果是新增左侧高亮
  2. 如果是编辑 左侧不需要高亮
*/
function Publish() {
  // url参数
  const params = useParams()
  // history
  const history = useHistory()
  console.log('params:', params)
  // 上传的文件列表 和上传组件绑定
  const [fileList, setFileList] = useState([])
  // 上传的文件信息 备份数组 额外的数据备份
  const [temFileList, setTemFileList] = useState([])
  // 最大上传张数
  const [max, setMax] = useState(1)

  // 验证成功
  const onFinish = async (values) => {
    // console.log('values:', values)
    // 组合数据
    const cover = {
      type: max,
      images: fileList.map((v) => v.url),
    }
    // 合并到一起
    // 一定不是草稿
    const draft = false
    // 数据
    const data = { ...values, cover }
    // 提交数据
    const res = await addAritcle(data, draft)
    // console.log('res:', res)
    message.success('新增成功')
    history.push('/home/article')
  }
  // 上传组件的change事件
  /*
    1. 触发多次
    2. 如果提交成功，最后可以获取到服务器的响应,response
  */
  const onUploadChange = (info) => {
    // console.log('info:', info)
    // 维护，更新数组
    const _fileList = info.fileList.map((file) => {
      if (file.response) {
        return {
          url: file.response.data.url,
        }
      } else {
        return file
      }
    })
    // 更新 hooks
    setFileList(_fileList)
    // 更新备份hooks
    setTemFileList(_fileList)
  }

  // 控制图片张数的change事件
  const onRadioChange = (event) => {
    // console.log('event:', event)
    const _max = event.target.value
    // 更新max的值
    setMax(_max)
    // 数组的长度应该和max的值匹配
    // 从备份数组中进行裁切，保证始终有一个备份在
    //  [...temFileList]  temFileList 不会在裁切的时候改变
    // const _fileList = [...temFileList].splice(0, _max)
    // map的作用返回一个新数组
    const _fileList = temFileList.map((v) => v).splice(0, _max)
    // console.log('_fileList:', _fileList)
    setFileList(_fileList)
  }

  return (
    <div className={style.publish}>
      <Card
        title={
          <Breadcrumb>
            <Breadcrumb.Item>
              <Link to='/home'>首页</Link>
            </Breadcrumb.Item>
            <Breadcrumb.Item>发布文章</Breadcrumb.Item>
          </Breadcrumb>
        }
      >
        <Form name='basic' labelCol={{ span: 4 }} wrapperCol={{ span: 20 }} initialValues={{ content: '', channel_id: 0 }} onFinish={onFinish} autoComplete='off'>
          <Form.Item wrapperCol={{ span: 6 }} label='标题' name='title' rules={[{ required: true, message: '标题不能为空' }]}>
            <Input placeholder='请输入文章的标题' />
          </Form.Item>

          <Form.Item wrapperCol={{ span: 6 }} label='频道' name='channel_id' rules={[{ required: true, message: '频道不能为空' }]}>
            <Channels />
          </Form.Item>
          <Form.Item wrapperCol={{ span: 6 }} label='封面'>
            <Radio.Group value={max} onChange={onRadioChange}>
              {types.map((v) => {
                return (
                  <Radio key={v.id} value={v.id}>
                    {v.value}
                  </Radio>
                )
              })}
            </Radio.Group>
          </Form.Item>
          <Form.Item wrapperCol={{ offset: 4, span: 6 }}>
            <Upload fileList={fileList} action='http://geek.itheima.net/v1_0/upload' name='image' onChange={onUploadChange} listType='picture-card' className='avatar-uploader'>
              {fileList.length < max && (
                <div style={{ marginTop: 8 }}>
                  <PlusOutlined />
                </div>
              )}
            </Upload>
          </Form.Item>
          {/* 设置了name之后，需要给默认值 */}
          <Form.Item label='内容' name='content' rules={[{ required: true, message: '内容不能为空' }]}>
            <ReactQuill placeholder='请输入文章的内容'></ReactQuill>
          </Form.Item>

          <Form.Item wrapperCol={{ offset: 4, span: 6 }}>
            <Button type='primary' htmlType='submit'>
              发布文章
            </Button>
            &nbsp; &nbsp;
            <Button htmlType='submit'>存入草稿</Button>
          </Form.Item>
        </Form>
      </Card>
    </div>
  )
}
export default Publish
